/* Copyright Andy Mitchell 2007. No warranties */

function GTDInboxDB(filename){
	this._statements = [];
	var file = Components.classes["@mozilla.org/file/directory_service;1"]
						.getService(Components.interfaces.nsIProperties)
						.get("ProfD", Components.interfaces.nsIFile);
	file.append(filename);

	var storageService = Components.classes["@mozilla.org/storage/service;1"]
							.getService(Components.interfaces.mozIStorageService);
	this.mDBConn = storageService.openDatabase(file);
}

GTDInboxDB.prototype.select = function(sql, f, debugForceErrorReport){
	try{
	var statement = this.mDBConn.createStatement(sql);
	// Process
	while( statement.executeStep() ){
		f( statement );
	}
	statement.reset();
	return true;
	}catch(e){
		if( GTDDEBUGMODE && (debugForceErrorReport || GTDDEBUGMODE_DB) ) alert("Fail Select\n" + sql + "\n\n\n" + e.toString());
	}
};

GTDInboxDB.prototype.execute = function(sql){
	//alert("execute:\n" + sql);
	try{
	this.mDBConn.executeSimpleSQL(sql);
	return true;
	}catch(e){
		if( GTDDEBUGMODE && GTDDEBUGMODE_DB ) alert("Fail Execute\n" + sql);
	}
};
GTDInboxDB.prototype.executeWithParams = function(sql, params){
	try{
	var s = this.mDBConn.createStatement(sql);
	for( var i = 0; i < params.length; i++ ){
		if( !params[i] ){
			s.bindNullParameter(i);
		}else if( typeof params[i]=="string" ){
			s.bindUTF8StringParameter(i, params[i]);
		}else if( typeof params[i]=="number" ){
			s.bindInt64Parameter(i, params[i]);
		}
	};
	s.execute();
	this._statements.push(s);
	}catch(e){if( GTDDEBUGMODE && GTDDEBUGMODE_DB ) alert("Fail execute params\n" + e.toString())}
};

GTDInboxDB.prototype.destroy = function(){
	// Close the connection
try{
	for( var i = this._statements.length - 1; i >= 0; i-- ){
		if( this._statements[i].finalize ) this._statements[i].finalize();
		this._statements.splice(i,1);
	}

	if( this.mDBConn ){
		if( this.mDBConn.close ) this.mDBConn.close();
		this.mDBConn = null;
	}
}catch(e){
	if( GTDDEBUGMODE ) alert("GTDInboxDB destroy\n" + e.toString());
}
};